<template>
  <div class="conversation-list-page">
    <el-page-header :icon="null" title="对话历史记录" content="查看和管理所有对话记录" />
    
    <!-- 搜索和筛选区 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="16">
        <el-input
          v-model="searchQuery"
          placeholder="搜索对话标题或内容..."
          prefix-icon="Search"
          @input="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </el-col>
      
      <el-col :span="8">
        <div style="text-align: right;">
          <el-button @click="refreshConversations">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 对话列表 -->
    <el-card style="margin-top: 20px;" v-loading="loading">
      <el-empty v-if="conversations.length === 0 && !loading" :description="searchQuery ? '未找到相关对话' : '暂无对话记录'" />
      
      <el-row :gutter="20" v-else class="conversation-grid">
        <el-col 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="8" 
          :xl="8"
          v-for="conversation in conversations" 
          :key="conversation.id"
          class="conversation-col"
        >
          <el-card shadow="hover" class="conversation-card" @click="viewConversation(conversation)">
            <template #header>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <h3 class="conversation-title">{{ conversation.title || '未命名对话' }}</h3>
                <el-tag v-if="conversation.isFavorited" type="warning" size="small">
                  <el-icon><Star /></el-icon>
                </el-tag>
              </div>
              <div class="conversation-meta">
                <span>{{ conversation.userName || conversation.userId }}</span>
                <span style="margin-left: 10px;">{{ formatTime(conversation.createdAt) }}</span>
              </div>
            </template>
            
            <div class="conversation-content">
              <p class="conversation-preview">
                {{ getConversationPreview(conversation) }}
              </p>
              <div class="conversation-stats">
                <span>消息数: {{ conversation.messageCount || 0 }}</span>
                <span>最后活动: {{ formatTime(conversation.lastMessageTime) }}</span>
              </div>
            </div>
            
            <template #footer>
              <div class="conversation-actions">
                <el-button size="small" @click.stop="viewConversation(conversation)">查看</el-button>
                <el-button size="small" type="danger" @click.stop="deleteConversation(conversation.id)">删除</el-button>
              </div>
            </template>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 加载更多提示 -->
      <div v-if="hasMoreData" class="load-more-trigger" id="load-more-trigger">
        <el-icon v-if="loadingMore" class="is-loading"><Loading /></el-icon>
        <span v-if="loadingMore" style="margin-left: 8px;">正在加载更多...</span>
        <span v-else>向下滚动加载更多</span>
      </div>
      
      <!-- 没有更多数据提示 -->
      <div v-if="!hasMoreData && conversations.length > 0" class="bottom-line">
        我也是有底线的
      </div>
    </el-card>

    <!-- 对话详情对话框 -->
    <el-dialog
      v-model="showConversationModal"
      :title="selectedConversation?.title || '对话详情'"
      width="80%"
      top="5vh"
    >
      <div v-if="selectedConversation">
        <el-descriptions :column="3" border style="margin-bottom: 20px;">
          <el-descriptions-item label="用户">
            {{ selectedConversation.userName || selectedConversation.userId }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatTime(selectedConversation.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后活动">
            {{ formatTime(selectedConversation.lastMessageTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="消息数量">
            {{ selectedConversation.messageCount || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="收藏状态">
            <el-tag :type="selectedConversation.isFavorited ? 'warning' : 'info'">
              {{ selectedConversation.isFavorited ? '已收藏' : '未收藏' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">对话内容</el-divider>
        <div v-loading="loadingMessages">
          <div v-if="conversationMessages.length === 0" style="text-align: center; color: #909399;">
            暂无消息
          </div>
          <div v-else>
            <div 
              v-for="message in conversationMessages" 
              :key="message.id"
              style="margin-bottom: 15px;"
            >
              <el-card shadow="never" :body-style="{ padding: '12px' }">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                  <el-tag :type="message.type === 'user' ? 'primary' : 'success'" size="small">
                    {{ message.type === 'user' ? '用户' : 'AI助手' }}
                  </el-tag>
                  <span style="color: #909399; font-size: 12px;">
                    {{ formatTime(message.createdAt) }}
                  </span>
                </div>
                <div style="line-height: 1.6;">{{ message.content }}</div>
              </el-card>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 统计信息 -->
    <el-card style="margin-top: 20px;">
      <template #header>
        <div style="display: flex; align-items: center;">
          <el-icon style="margin-right: 8px;"><DataAnalysis /></el-icon>
          <span style="font-weight: 600;">统计信息</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <el-statistic title="总对话数" :value="totalConversations" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="今日对话" :value="todayConversations" />
        </el-col>
        <el-col :span="8">
          <el-statistic title="活跃用户" :value="activeUsers" />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Star, DataAnalysis, Loading } from '@element-plus/icons-vue'
import { conversationApi, messageApi, userApi } from '@/api'

const conversations = ref([])
const conversationMessages = ref([])
const loading = ref(false)
const loadingMessages = ref(false)
const searchQuery = ref('')

// 分页和无限滚动
const currentPage = ref(1)
const pageSize = ref(12) // 卡片布局，每页显示12个
const totalConversations = ref(0)
const loadingMore = ref(false)
const hasMoreData = ref(true)

const totalPages = computed(() => Math.ceil(totalConversations.value / pageSize.value))

// 模态框相关
const showConversationModal = ref(false)
const selectedConversation = ref(null)

// 统计数据
const todayConversations = ref(0)
const activeUsers = ref(0)

// 获取对话列表
const fetchConversations = async (page = 1, append = false) => {
  if (append) {
    loadingMore.value = true
  } else {
    loading.value = true
  }
  
  try {
    // 使用分页API获取对话列表
    const result = await conversationApi.getAllConversationsPaged(page, pageSize.value)
    let pagedData
    
    if (result && result.items) {
      // 后端返回的是分页结果对象
      pagedData = result
    } else if (result && result.data && result.data.items) {
      // 后端返回的是包装在data中的分页结果
      pagedData = result.data
    } else {
      // 兼容旧的非分页API返回格式 - 这种情况下所有数据都在第一页
      const conversationsData = Array.isArray(result) ? result : (result.data || [])
      const totalCount = conversationsData.length
      const actualItems = conversationsData.slice((page - 1) * pageSize.value, page * pageSize.value)
      
      pagedData = {
        items: actualItems,
        currentPage: page,
        pageSize: pageSize.value,
        totalCount: totalCount,
        totalPages: Math.ceil(totalCount / pageSize.value)
      }
      
      console.log(`兼容模式: 总数据=${totalCount}, 当前页=${page}, 页面大小=${pageSize.value}, 总页数=${Math.ceil(totalCount / pageSize.value)}, 当前页数据=${actualItems.length}`)
    }
    
    const conversationsData = pagedData.items || []
    
    // 更新分页信息
    currentPage.value = pagedData.currentPage || page
    if (!append) {
      totalConversations.value = pagedData.totalCount || 0
    }
    
    // 检查是否还有更多数据
    const totalPages = pagedData.totalPages || 1
    const currentPageItemCount = conversationsData.length
    
    // 判断是否还有更多数据：当前页小于总页数
    hasMoreData.value = currentPage.value < totalPages
    
    console.log(`当前页: ${currentPage.value}, 总页数: ${totalPages}, 当前页数据量: ${currentPageItemCount}, 页面大小: ${pageSize.value}, 还有更多数据: ${hasMoreData.value}`)
    
    // 为每个对话获取消息数量和最后消息时间
    const conversationsWithDetails = await Promise.all(
      conversationsData.map(async (conv) => {
        try {
          // 获取对话的消息
          const messages = await messageApi.getMessagesByConversationId(conv.id)
          const messageList = Array.isArray(messages) ? messages : (messages.data || [])
          
          // 计算消息数量和最后消息时间
          const messageCount = messageList.length
          const lastMessage = messageList.length > 0 
            ? messageList.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))[0]
            : null
          
          // 生成预览文本
          const preview = lastMessage 
            ? `${lastMessage.sender}: ${lastMessage.content.substring(0, 50)}...`
            : '暂无消息'
          
          // 获取用户信息
          let userName = `用户 ${conv.userId.substring(0, 8)}`
          try {
            const userInfo = await userApi.getUserById(conv.userId)
            if (userInfo && userInfo.username) {
              userName = userInfo.username
            } else if (userInfo && userInfo.data && userInfo.data.username) {
              userName = userInfo.data.username
            }
          } catch (userError) {
            console.warn(`获取用户 ${conv.userId} 信息失败，使用默认显示`, userError)
          }
            
          return {
            ...conv,
            messageCount,
            lastMessageTime: lastMessage ? lastMessage.createdAt : conv.createdAt,
            preview,
            title: conv.title || `对话 ${conv.id.substring(0, 8)}`,
            userName,
            isFavorited: conv.isCollected || false
          }
        } catch (error) {
          console.error(`获取对话 ${conv.id} 的消息失败:`, error)
          
          // 获取用户信息（即使消息获取失败也要尝试获取用户名）
          let userName = `用户 ${conv.userId.substring(0, 8)}`
          try {
            const userInfo = await userApi.getUserById(conv.userId)
            if (userInfo && userInfo.username) {
              userName = userInfo.username
            } else if (userInfo && userInfo.data && userInfo.data.username) {
              userName = userInfo.data.username
            }
          } catch (userError) {
            console.warn(`获取用户 ${conv.userId} 信息失败，使用默认显示`, userError)
          }
          
          return {
            ...conv,
            messageCount: 0,
            lastMessageTime: conv.createdAt,
            preview: '暂无预览',
            title: conv.title || `对话 ${conv.id.substring(0, 8)}`,
            userName,
            isFavorited: conv.isCollected || false
          }
        }
      })
    )
    
    // 根据是否追加模式来处理数据
    if (append) {
      // 追加模式：将新数据添加到现有数据后面
      conversations.value = [...conversations.value, ...conversationsWithDetails]
    } else {
      // 替换模式：直接替换所有数据
      conversations.value = conversationsWithDetails
    }
    
    // 计算统计数据（基于当前页的数据）
    if (!append) {
      calculateStats()
    }
    
    // 重新设置 Intersection Observer
    await nextTick()
    setupIntersectionObserver()
  } catch (error) {
    console.error('获取对话列表失败:', error)
    ElMessage.error('获取对话列表失败，请检查网络连接')
    
    if (!append) {
      // 清空数据而不是使用模拟数据
      conversations.value = []
      totalConversations.value = 0
      calculateStats()
    }
  } finally {
    if (append) {
      loadingMore.value = false
    } else {
      loading.value = false
    }
  }
}

// 加载更多数据
const loadMoreConversations = async () => {
  console.log(`loadMoreConversations 调用: loadingMore=${loadingMore.value}, hasMoreData=${hasMoreData.value}, currentPage=${currentPage.value}`)
  
  if (loadingMore.value || !hasMoreData.value) {
    console.log('loadMoreConversations 被阻止执行')
    return
  }
  
  const nextPage = currentPage.value + 1
  console.log(`开始加载第 ${nextPage} 页数据`)
  
  try {
    await fetchConversations(nextPage, true)
    console.log(`第 ${nextPage} 页加载成功，新的状态: currentPage=${currentPage.value}, hasMoreData=${hasMoreData.value}, 当前对话总数=${conversations.value.length}`)
  } catch (error) {
    console.error(`加载第 ${nextPage} 页失败:`, error)
    ElMessage.error('加载更多数据失败')
  }
}

// 滚动监听 - 监听页面主滚动条
let scrollTimeout = null
let intersectionObserver = null

const handlePageScroll = () => {
  if (scrollTimeout) clearTimeout(scrollTimeout)
  
  scrollTimeout = setTimeout(() => {
    // 获取页面滚动信息
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    const windowHeight = window.innerHeight || document.documentElement.clientHeight
    const documentHeight = Math.max(
      document.body.scrollHeight,
      document.body.offsetHeight,
      document.documentElement.clientHeight,
      document.documentElement.scrollHeight,
      document.documentElement.offsetHeight
    )
    
    // 计算滚动到底部的距离
    const distanceToBottom = documentHeight - (scrollTop + windowHeight)
    const scrollPercentage = (scrollTop + windowHeight) / documentHeight
    
    console.log(`页面滚动 - 距离底部: ${distanceToBottom}px, 滚动百分比: ${(scrollPercentage * 100).toFixed(2)}%`)
    console.log(`loadingMore: ${loadingMore.value}, hasMoreData: ${hasMoreData.value}, currentPage: ${currentPage.value}`)
    
    // 当距离底部小于200px或滚动到90%位置时加载更多
    if ((distanceToBottom < 200 || scrollPercentage > 0.9) && !loadingMore.value && hasMoreData.value) {
      console.log('触发加载更多')
      loadMoreConversations()
    }
  }, 200) // 200ms防抖
}

// 设置 Intersection Observer 作为备用方案
const setupIntersectionObserver = () => {
  if (intersectionObserver) {
    intersectionObserver.disconnect()
  }
  
  intersectionObserver = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && !loadingMore.value && hasMoreData.value) {
          console.log('Intersection Observer 触发加载更多')
          loadMoreConversations()
        }
      })
    },
    {
      rootMargin: '100px' // 提前100px触发
    }
  )
  
  // 观察加载更多触发器
  const loadMoreTrigger = document.getElementById('load-more-trigger')
  if (loadMoreTrigger) {
    intersectionObserver.observe(loadMoreTrigger)
    console.log('已设置 Intersection Observer')
  }
}

// 搜索对话
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    // 重置搜索，重新加载第一页数据
    currentPage.value = 1
    hasMoreData.value = true
    conversations.value = []
    fetchConversations(1, false)
    return
  }
  
  // 本地搜索，实际项目中应该调用后端搜索API
  // 注意：搜索时暂时禁用无限滚动，因为本地搜索无法分页
  hasMoreData.value = false
  const allConversations = conversations.value
  const filtered = allConversations.filter(conv => 
    (conv.title && conv.title.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
    (conv.preview && conv.preview.toLowerCase().includes(searchQuery.value.toLowerCase()))
  )
  conversations.value = filtered
}

// 查看对话详情
const viewConversation = async (conversation) => {
  selectedConversation.value = conversation
  showConversationModal.value = true
  
  // 获取对话消息
  loadingMessages.value = true
  try {
    const messages = await messageApi.getMessagesByConversationId(conversation.id)
    const messageList = Array.isArray(messages) ? messages : (messages.data || [])
    
    // 转换消息格式，将用户消息和AI回复分开显示
    const conversationMessagesFormatted = []
    messageList.forEach(msg => {
      // 添加用户消息
      if (msg.content) {
        conversationMessagesFormatted.push({
          id: `${msg.id}-user`,
          type: 'user',
          content: msg.content,
          createdAt: msg.createdAt
        })
      }
      
      // 添加AI回复
      if (msg.reply) {
        conversationMessagesFormatted.push({
          id: `${msg.id}-assistant`,
          type: 'assistant',
          content: msg.reply,
          createdAt: msg.createdAt
        })
      }
    })
    
    // 按时间排序
    conversationMessages.value = conversationMessagesFormatted.sort(
      (a, b) => new Date(a.createdAt) - new Date(b.createdAt)
    )
  } catch (error) {
    console.error('获取对话消息失败:', error)
    ElMessage.error('获取对话消息失败')
    conversationMessages.value = []
  } finally {
    loadingMessages.value = false
  }
}

// 导出对话
const exportConversation = async (conversation) => {
  try {
    // TODO: 实现导出功能
    ElMessage.success(`导出对话: ${conversation.title}`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 切换收藏状态
const toggleFavorite = async (conversation) => {
  try {
    if (conversation.isFavorited) {
      await conversationApi.unfavoriteConversation(conversation.id)
      conversation.isFavorited = false
    } else {
      await conversationApi.favoriteConversation(conversation.id)
      conversation.isFavorited = true
    }
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    // 本地切换状态
    conversation.isFavorited = !conversation.isFavorited
  }
}

// 删除对话
const deleteConversation = async (conversationId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？此操作不可恢复！', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await conversationApi.deleteConversation(conversationId)
    await fetchConversations()
    ElMessage.success('对话删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除对话失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 刷新对话列表
const refreshConversations = () => {
  searchQuery.value = ''
  currentPage.value = 1
  hasMoreData.value = true
  loadingMore.value = false
  conversations.value = []
  console.log('刷新对话列表，重置所有状态')
  fetchConversations(1, false)
}

// 关闭对话详情模态框
const closeConversationModal = () => {
  showConversationModal.value = false
  selectedConversation.value = null
  conversationMessages.value = []
}

// 获取对话预览
const getConversationPreview = (conversation) => {
  // 如果有预览内容，直接返回
  if (conversation.preview && conversation.preview.trim()) {
    return conversation.preview.length > 100 ? conversation.preview.substring(0, 100) + '...' : conversation.preview
  }
  
  // 如果消息数为0，显示暂无消息
  if (!conversation.messageCount || conversation.messageCount === 0) {
    return '暂无消息'
  }
  
  // 如果有标题但没有预览，使用标题
  if (conversation.title && conversation.title.trim()) {
    return `对话主题：${conversation.title}`
  }
  
  // 默认情况
  return '暂无预览内容'
}

// 计算统计数据
const calculateStats = () => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  
  todayConversations.value = conversations.value.filter(conv => 
    new Date(conv.createdAt) >= today
  ).length
  
  const uniqueUsers = new Set(conversations.value.map(conv => conv.userId))
  activeUsers.value = uniqueUsers.size
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '无'
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString('zh-CN')
}

onMounted(async () => {
  await fetchConversations(1)
  
  // 添加页面滚动监听
  window.addEventListener('scroll', handlePageScroll)
  
  // 设置 Intersection Observer
  await nextTick() // 确保DOM已渲染
  setupIntersectionObserver()
  
  // 添加调试信息
  console.log('页面加载完成，已添加滚动监听和 Intersection Observer')
  
  // 5秒后检查滚动状态
  setTimeout(() => {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    const windowHeight = window.innerHeight || document.documentElement.clientHeight
    const documentHeight = Math.max(
      document.body.scrollHeight,
      document.body.offsetHeight,
      document.documentElement.clientHeight,
      document.documentElement.scrollHeight,
      document.documentElement.offsetHeight
    )
    console.log(`5秒后检查 - 滚动位置: ${scrollTop}, 窗口高度: ${windowHeight}, 文档高度: ${documentHeight}`)
    console.log(`页面是否可滚动: ${documentHeight > windowHeight}`)
  }, 5000)
})

onUnmounted(() => {
  // 移除滚动监听器
  window.removeEventListener('scroll', handlePageScroll)
  
  // 断开 Intersection Observer
  if (intersectionObserver) {
    intersectionObserver.disconnect()
  }
  
  // 清理定时器
  if (scrollTimeout) {
    clearTimeout(scrollTimeout)
  }
})
</script>

<style scoped>
/* 页面容器样式优化 */
.conversation-list-page {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

/* 确保没有容器滚动条，只使用页面主滚动条 */
.conversation-card {
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  margin-bottom: 20px;
  height: 100%;
  min-height: 320px; /* 增加最小高度，确保视觉一致性 */
  max-height: 320px; /* 设置最大高度，确保所有卡片高度一致 */
  display: flex;
  flex-direction: column;
  width: 100%; /* 确保卡片填满容器宽度 */
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
}

.conversation-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(99, 102, 241, 0.15);
}

/* 优化卡片内容布局 */
.conversation-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 140px;
  padding: 16px;
}

/* 优化卡片footer布局 */
.conversation-card :deep(.el-card__footer) {
  margin-top: auto;
  padding: 12px 16px;
  background-color: #fafbfc;
  border-top: 1px solid #f0f2f5;
}

/* 卡片内容布局 */
.conversation-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 120px;
  max-height: 120px; /* 限制内容区域最大高度 */
  flex: 1;
}

.conversation-preview {
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.5;
  flex: 1;
  min-height: 80px; /* 增加预览文本的最小高度 */
  max-height: 80px; /* 限制预览文本的最大高度 */
  display: -webkit-box;
  -webkit-line-clamp: 4; /* 增加到4行显示 */
  line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-size: 14px;
  text-align: left;
}

/* 为"暂无消息"的情况特殊处理 */
.conversation-preview:empty::before {
  content: "暂无消息";
  color: #c0c4cc;
  font-style: italic;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.conversation-stats {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 12px;
  margin-top: auto;
  padding-top: 8px;
  border-top: 1px solid #f5f7fa;
}

/* 卡片头部样式优化 */
.conversation-card :deep(.el-card__header) {
  min-height: 90px;
  max-height: 90px; /* 限制头部最大高度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e2e8f0;
}

/* 确保标题区域统一高度 */
.conversation-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  line-height: 1.4;
  min-height: 24px;
  max-height: 48px; /* 限制标题最大高度 */
  color: #1f2937;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.conversation-meta {
  margin-top: 8px;
  color: #6b7280;
  font-size: 12px;
  display: flex;
  align-items: center;
  min-height: 20px;
}

/* 美化收藏标签 */
.conversation-card .el-tag {
  border-radius: 12px;
  font-size: 11px;
}

/* 优化按钮区域 */
.conversation-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.conversation-actions .el-button {
  border-radius: 6px;
  font-size: 12px;
  padding: 4px 12px;
  border: 1px solid #d1d5db;
  background-color: #ffffff;
  color: #374151;
  transition: all 0.2s;
}

.conversation-actions .el-button:hover {
  background-color: #f3f4f6;
  border-color: #6366f1;
  color: #6366f1;
}

.conversation-actions .el-button--danger {
  border-color: #fca5a5;
  color: #dc2626;
}

.conversation-actions .el-button--danger:hover {
  background-color: #fef2f2;
  border-color: #ef4444;
}

.conversation-actions .el-button--warning {
  border-color: #fcd34d;
  color: #d97706;
}

.conversation-actions .el-button--warning:hover {
  background-color: #fefbf2;
  border-color: #f59e0b;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .conversation-col {
    width: calc(50% - 10px); /* 中等屏幕显示2列 */
  }
}

@media (max-width: 768px) {
  .conversation-col {
    width: 100%; /* 小屏幕显示1列 */
    padding: 0 5px;
  }
  
  .conversation-card {
    min-height: 280px;
    max-height: 280px;
  }
  
  .conversation-actions {
    flex-wrap: wrap;
    gap: 6px;
  }
  
  .conversation-actions .el-button {
    flex: 1;
    min-width: calc(50% - 3px);
    font-size: 11px;
  }
}

/* 优化卡片动画 */
@media (prefers-reduced-motion: reduce) {
  .conversation-card {
    transition: none;
  }
  
  .conversation-card:hover {
    transform: none;
  }
}

/* 优化卡片容器布局 */
.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

/* 确保对话详情弹窗内容不产生滚动条 */
.el-dialog__body {
  max-height: none !important;
  overflow: visible !important;
}

/* 优化页面布局，防止不必要的滚动条 */
.conversation-grid {
  margin: 0 !important;
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.conversation-col {
  padding: 0 10px;
  margin-bottom: 20px;
  display: flex;
  width: calc(33.333% - 13.33px); /* 确保每行3个，宽度完全一致 */
  min-width: 0; /* 防止flex子元素超出容器 */
}

.el-row {
  margin: 0 !important;
  width: 100%;
}

/* 加载提示样式优化 */
.load-more-trigger {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.bottom-line {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
}

/* 搜索区域样式 */
.el-page-header {
  margin-bottom: 0;
}
</style>